import {iBaseType} from "../components/base.type";
import {useTableOption} from "../../modules/plain-design/useTableOption";
import {usePageService} from "../../modules/micro/usePageService";
import {usePageConfig} from "../../micro/MicroApp.pageConfig";
import {microApp} from "../../microApp";
import {usePageButton} from "../../micro/MicroApp.pageButton";
import {deepcopy} from "@peryl/utils/deepcopy";
import {pathJoin} from "@peryl/micro-web";
import {$dialog, Form, FormInput} from "plain-design";
import {designComponent, PropType, useRefs} from "@peryl/react-compose";
import {defer} from "@peryl/utils/defer";

export interface iCodeGeneratorRecord extends Partial<iBaseType> {
  title?: string,
  remarks?: string,
  code?: string,
  image?: string,
}

export const codeGeneratorResourceGetter = async (name: string) => {
  if (name === 'base') {return { useTableOption, usePageService, usePageConfig, usePageButton, deepcopy, pathJoin };}
  const module = await microApp.resource.load(name, window);
  if (name === '@peryl/react-compose') {
    (window as any).PlainDesignComposition = module;
  }
  return module;
};

export function openCodeGenRecordEditor(record: iCodeGeneratorRecord) {
  record = deepcopy(record);
  let refer: any;
  const dfd = defer<iCodeGeneratorRecord>();
  $dialog({
    title: '编辑信息',
    onClose: () => {refer = null;},
    confirmButton: true,
    cancelButton: true,
    render: () => (
      <CodeGenRecordEditor record={record} onRef={(val: any) => refer = val}/>
    ),
    handleConfirm: async () => {
      await refer.refs.form.validate();
      dfd.resolve(record);
    },
    handleCancel: () => {dfd.reject('cancel');}
  });
  return dfd.promise;
}

const CodeGenRecordEditor = designComponent({
  props: {
    record: { type: Object as PropType<iCodeGeneratorRecord>, required: true },
  },
  setup({ props }) {

    const { refs, onRef } = useRefs({ form: Form });

    return {
      refer: {
        refs,
      },
      render: () => (
        <Form column={1} ref={onRef.form} validateMessagePosition="bottom-right">
          <FormInput label="标题" v-model={props.record.title} required/>
          <FormInput label="备注" v-model={props.record.remarks} textarea/>
        </Form>
      )
    };
  },
});
